package com.rainy.sso.common.service;

import com.rainy.sso.client.entity.*;
import com.rainy.sso.client.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import com.rainy.sso.common.dao.UserDao;
import org.springframework.util.CollectionUtils;

/**
* @author liuqin on 2017-12-21 14:26:10
*/
@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	private UserDao userDao;

	@Resource
	private UserRoleService userRoleService;

	@Resource
	private RoleService roleService;

	@Resource
	private RolePermissionService rolePermissionService;

	@Resource
	private PermissionService permissionService;

    @Override
    public List<User> list(Long offset, Long limit){
		return userDao.list(offset,limit);
	}

    @Override
    public Long count(Long offset,Long limit){
        return userDao.count(offset,limit);
	}

    @Override
    public User getUserById(Long id){
        return userDao.queryUserById(id);
	}
	
	@Override
	public void save(User user){
		userDao.save(user);
	}
	
	@Override
	public void update(User user){
		userDao.update(user);
	}
	
	@Override
	public void delete(Long id){
		userDao.delete(id);
	}

	@Override
	public List<String> getPermissionsByUserName() {
		return null;
	}

	@Override
	public User queryUserByUserName(String username) {
		User user = this.queryUserInfo(username);
		List<UserRole> userRoles = userRoleService.queryUserRoleByUid(user.getId());
		if (!CollectionUtils.isEmpty(userRoles)){
			Set<Role> roles = roleService.queryRoleByIds(userRoles.stream().map(UserRole::getRid).collect(Collectors.toList()));
			user.setRoles(roles);
			List<RolePermission> rolePermissions = rolePermissionService.queryRolePermissionByRids(roles.stream().map(Role::getId).collect(Collectors.toList()));
			Set<Permission> permissions = permissionService.queryPermissionByIds(rolePermissions.stream().map(RolePermission::getPid).collect(Collectors.toList()));
			user.setPermissions(permissions);
		}
		return user;
	}

	@Override
	public User queryUserInfo(String username) {
		return userDao.queryUserByUserName(username);
	}


}
